<?php
require_once('classes/apprenant.php');

class Apprenant extends PDO {
	const TABLE = 'Apprenant';
	const ID = 'idApprenant';
	const LANGUE = 'idLangue';
	const NOM = 'nom';

	private $connection;
	private $stmt_select_by_id;
	private $stmt_select_by_name;
	private $stmt_save;
	private $stmt_create;
	private $stmt_delete;

	public function __construct($connection) {
		$this->connection = $connection;
		$this->prepare_statements();
	}

	public static function getTableName() {
		return TABLE;
	}

	public function getBeanById($id) {
		$this->stmt_select_by_id->bindParam(':id', $id, PDO::PARAM_INT);
		$this->stmt_select_by_id->execute();

		return $this->stmt_select_by_id->fetchObject('ApprenantBean');
	}

	public function getListByNom($nom) {
		$this->stmt_select_by_name->bindParam(':nom', $nom, PDO::PARAM_STR);
		$this->stmt_select_by_name->execute();

		return $this->stmt_select_by_name->fetchAll(PDO::FETCH_CLASS, 'ApprenantBean');
	}

	public function saveBean($bean) {
		$this->stmt_save->bindParam(':id', $bean->getIdApprenant(), PDO::PARAM_INT);
		$this->stmt_save->bindParam(':nom', $bean->getNom(), PDO::PARAM_STR);
		$this->stmt_save->bindParam(':lang', $bean->getIdLangue(), PDO::PARAM_INT);
		$this->stmt_save->execute();

		return $this->getBeanById($bean->getIdApprenant());
	}

	public function createBean($nom, $langue) {
		$this->stmt_create->bindParam(':nom', $nom, PDO::PARAM_STR);
		$this->stmt_create->bindParam(':lang', $langue, PDO::PARAM_INT);
		$this->stmt_create->execute();

		return $this->getBeanById($this->connection->lastInsertId());
	}

	public function deleteBeanById($id) {
		$this->stmt_delete->bindParam(':id', $id, PDO::PARAM_INT);
		return $this->stmt_delete->execute();
	}

	private function prepare_statements() {
		$sql = 'SELECT '.self::ID.','.self::NOM.','.self::LANGUE.
			' FROM '.self::TABLE.
			' WHERE '.self::ID.' = :id';
		$this->stmt_select_by_id = $this->connection->prepare($sql);

		$sql = 'SELECT '.self::ID.','.self::NOM.','.self::LANGUE.
			' FROM '.self::TABLE.
			' WHERE '.self::NOM.' LIKE :nom';
		$this->stmt_select_by_name = $this->connection->prepare($sql);

		$sql = 'UPDATE '.self::TABLE.
			' SET '.self::NOM.' = :nom, '.self::LANGUE.' = :lang'.
			' WHERE '.self::ID.' = :id';
		$this->stmt_save = $this->connection->prepare($sql);

		$sql = 'INSERT INTO '.self::TABLE.' ( '.self::NOM.' , '.self::LANGUE.' )'.
			' VALUES ( :nom , :lang )';
		$this->stmt_create = $this->connection->prepare($sql);

		$sql = 'DELETE FROM '.self::TABLE.' WHERE '.self::ID.' = :id';
		$this->stmt_delete = $this->connection->prepare($sql);
	}
}
?>
